/*
 * @Author: zhoulei0232
 * @Date: 2021-06-16 17:30:07
 * @LastEditTime: 2021-06-30 17:31:53
 * @LastEditors: zhoulei0232
 * @Description:
 */

import axios, { AxiosResponse, AxiosRequestConfig } from "axios";
import config from "../config";
import { ElMessage, ElLoading } from "element-plus";
import { showLoading, hideLoading } from "./loading";

const service = axios.create({
  baseURL: config.baseApi,
  headers: {
    "Content-Type": "application/json",
  },
  timeout: 8000,
});

interface ServiceRequestConfig extends AxiosRequestConfig {
  loading?: boolean;
  ele?: any;
}

// 请求拦截
service.interceptors.request.use(
  (config: ServiceRequestConfig) => {
    // 请求拦截进来调用显示loading效果
    console.log(1123, config);

    if (config.loading) {
      showLoading(config.ele);
    }
    // if (localStorage.getItem("token")) {
    //   config.headers.token = localStorage.getItem("token"); //让请求头携带验证token
    //   config.headers.admin = localStorage.getItem("user"); // 让每个请求携带自定义token 请根据实际情况自行修改
    // }
    return config;
  },
  (err: any) => {
    Promise.reject(err);
  }
);
// 响应拦截
service.interceptors.response.use(
  (response: AxiosResponse) => {
    // 响应拦截进来隐藏loading效果，此处采用延时处理是合并loading请求效果，避免多次请求loading关闭又开启
    setTimeout(() => {
      hideLoading();
    }, 500);
    console.log(response);
    if (response.status !== 200) {
      return { code: 100 };
    } else {
      let res = response.data;
      return res;
    }
  },
  (err: any) => {
    return { code: 100 };
  }
);
/**
 * 请求核心函数
 * @param {*} options 请求配置
 */
function request(options: any) {
  options.method = options.method || "get";
  if (options.method.toLowerCase() === "get") {
    options.params = options.data;
  }
  let isMock = config.mock;
  if (typeof options.mock != "undefined") {
    isMock = options.mock;
  }
  if (config.env === "prod") {
    service.defaults.baseURL = config.baseApi;
  } else {
    service.defaults.baseURL = isMock ? config.mockApi : config.baseApi;
  }

  return service(options);
}

export default request;
